package com.example.springfastjsonsample

import com.alibaba.fastjson.serializer.SerializerFeature
import com.alibaba.fastjson.support.config.FastJsonConfig
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.http.HttpMessageConverters
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.MediaType


/**
 * @Configuration注解可以让springboot自动装载类：让SpringBoot自动加载类内的配置。
 */
@Configuration
class FastjsonConfiguration {
    @Bean
    @ConditionalOnMissingBean
    fun fastJsonHttpMessageConverters(): HttpMessageConverters {
        val fastConverter = FastJsonHttpMessageConverter()
        //创建fastJson配置实体类
        val fastJsonConfig = FastJsonConfig()
        fastJsonConfig.setSerializerFeatures( //消除对同一对象循环引用的问题，默认为false
            SerializerFeature.DisableCircularReferenceDetect,  //是否输出值为null的字段,默认为false
            SerializerFeature.WriteMapNullValue,  //List字段如果为null,输出为[],而非null
            SerializerFeature.WriteNullListAsEmpty,  //字符类型字段如果为null,输出为"",而非null
            SerializerFeature.WriteNullStringAsEmpty,  //数值字段如果为null,输出为0,而非null
            SerializerFeature.WriteNullNumberAsZero,  //全局修改日期格式
            SerializerFeature.WriteDateUseDateFormat,  //Boolean字段如果为null,输出为false,而非null
            SerializerFeature.WriteNullBooleanAsFalse
        )
        val fastMediaTypes: MutableList<MediaType> = ArrayList<MediaType>()
        //标准化输出json格式的字符编码，设置为utf-8
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8)
        fastConverter.setSupportedMediaTypes(fastMediaTypes)
        fastConverter.setFastJsonConfig(fastJsonConfig)
        return HttpMessageConverters(fastConverter)
    }
}